package com.ruoyi.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginApiBody;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sms.SendSms;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysUserService;

import io.jsonwebtoken.lang.Assert;

@RestController
@RequestMapping("/api/user")
public class UserAppController {
	@Autowired
	private SendSms sms;
	@Autowired
	private SysLoginService loginService;
	@Autowired
	private SysRegisterService registerService;
	@Autowired
	private ISysUserService userService;
	@PostMapping("/login")
	public AjaxResult login(@RequestBody LoginApiBody data) {
		AjaxResult ajax = AjaxResult.success();
		String mobile = data.getMobile();
		String code = data.getCode();
		Assert.isTrue(StringUtils.isNotBlank(mobile), "手机号必填");
		Assert.isTrue(StringUtils.isNotBlank(code), "验证码必填");
		boolean flag = sms.isAvailable(mobile, code);
		Assert.isTrue(flag, "验证码错误");
		SysUser userByPhone = userService.getUserByPhone(mobile);
		if(userByPhone!=null) {//用户存在  登录
			// 生成令牌
			String token = loginService.loginBySms(userByPhone.getUserName(), userByPhone.getPhonenumber());
			ajax.put(Constants.TOKEN, token);
		}else {//注册
			LoginBody loginBody = new LoginBody();
			loginBody.setUsername(data.getMobile());
			loginBody.setPassword(data.getMobile());//初始密码手机号
			String registerBysms = registerService.registerBysms(loginBody);
			ajax.put("msg", registerBysms);
			if("成功".equals(registerBysms)) {
				String token = loginService.loginBySms(data.getMobile(), data.getMobile());
				ajax.put(Constants.TOKEN, token);
			}
		}
		return ajax;
		
	}
}
